import { isString, isArray } from '@/utils'
import { Message } from 'element-ui'
import { globalThemeJson } from '@/settings'
import { loadingStart, loadingFinish } from '@/utils'


const state = {
  // 画布属性
  editCanvas: {
    // 编辑区域 Dom
    editLayoutDom: null,
    editContentDom: null,
    // 偏移量
    offset: 20,
    // 系统控制缩放
    scale: 1,
    // 用户控制的缩放
    userScale: 1,
    // 锁定缩放
    lockScale: false,
    // 初始化
    isCreate: false,
    // 拖拽中
    isDrag: false,
    // 框选中
    isSelect: false,
    // 代码编辑中
    isCodeEdit: false
  },
  // 画布属性（需存储给后端）
  editCanvasConfig: {
    // 项目名称
    projectName: undefined,
    // 默认宽度
    width: 1920,
    // 默认高度
    height: 1080,
    // 启用滤镜
    filterShow: false,
    // 色相
    hueRotate: 0,
    // 饱和度
    saturate: 1,
    // 对比度
    contrast: 1,
    // 亮度
    brightness: 1,
    // 透明度
    opacity: 1,
    // 变换（暂不更改）
    rotateZ: 0,
    rotateX: 0,
    rotateY: 0,
    skewX: 0,
    skewY: 0,
    // 混合模式
    blendMode: 'normal',
    // 默认背景色
    background: undefined,
    backgroundImage: undefined,
    // 是否使用纯颜色
    selectColor: true,
    // chart 主题色
    chartThemeColor: 'dark',
    // 全局配置
    chartThemeSetting: globalThemeJson,
    // 自定义颜色列表
    chartCustomThemeColorInfo: undefined,
  },
  // 目标图表
  targetChart: {
    hoverId: undefined,
    selectId: []
  },
  // 图表数组（需存储给后端）
  componentList: [],
  // 鼠标定位
  mousePosition: {
    startX: 0,
    startY: 0,
    x: 0,
    y: 0
  },
  // 数据请求处理（需存储给后端）
  requestGlobalConfig: {
    requestDataPond: [],
    requestOriginUrl: '',
    requestInterval: 30,
    requestIntervalUnit: 'second',
    requestParams: {
      Body: {
        'form-data': {},
        'x-www-form-urlencoded': {},
        json: '',
        xml: ''
      },
      Header: {},
      Params: {}
    }
  },
}

const mutations = {
  setEditCanvas (state, { key, value }) {
    state.editCanvas[key] = value
  },
  // 设置目标数据 select
  setTargetSelectChart (state, { id, push = false }) {
    // 重复选中
    if (state.targetChart.selectId.find(e => e === id)) return

    // 无 id 清空
    if (!id) {
      state.targetChart.selectId = []
      return
    }
    // 多选
    if (push) {
      // 字符串
      if (isString(id)) {
        state.targetChart.selectId.push(id)
        return
      }
      // 数组
      if (isArray(id)) {
        state.targetChart.selectId.push(...id)
        return
      }
    } else {
      // 字符串
      if (isString(id)) {
        state.targetChart.selectId = [id]
        return
      }
      // 数组
      if (isArray(id)) {
        state.targetChart.selectId = id
        return
      }
    }
  },
  /**
* * 新增组件列表
* @param componentInstance 新图表实例
* @param isHead 是否头部插入
* @param isHistory 是否进行记录
* @returns
*/
  addComponentList (state,
    { componentInstance,
      isHead = false,
      isHistory = false }
  ) {
    if (componentInstance instanceof Array) {
      componentInstance.forEach(item => {
        this.commit('chartEdit/addComponentList', { componentInstance: item, isHead, isHistory })
      })
      return
    }
    if (isHead) {
      state.componentList.unshift(componentInstance)
      return
    }
    state.componentList.push(componentInstance)
  },
  /**
* * 设置缩放
* @param scale 0~1 number 缩放比例;
* @param force boolean 强制缩放
*/
  setScale (state, { scale, force = false }) {
    if (!state.editCanvas.lockScale || force) {
      const dom = state.editCanvas.editContentDom
      if (dom) {
        dom.style.height = state.editCanvasConfig.height * scale + 'px'
        dom.style.width = state.editCanvasConfig.width * scale + 'px'
      }
      state.editCanvas.userScale = scale
      state.editCanvas.scale = scale
    }
  },
  // 设置鼠标位置
  setMousePosition (state, { x, y, startX, startY }) {
    if (x) state.mousePosition.x = x
    if (y) state.mousePosition.y = y
    if (startX) state.mousePosition.startX = startX
    if (startY) state.mousePosition.startY = startY
  },
  // 设置目标数据 hover
  setTargetHoverChart (state, hoverId) {
    state.targetChart.hoverId = hoverId
  },
  // 删除组件
  async removeComponentList (state, id) {
    try {
      const idArr = await this.dispatch('chartEdit/idPreFormat', id)
      // 遍历所有对象
      if (!idArr.length) return

      loadingStart()
      idArr.forEach(ids => {
        const index = this.getters['chartEdit/fetchTargetIndex'](ids)
        if (index !== -1) {
          state.componentList.splice(index, 1)
        }
      })
      loadingFinish()
      return
    } catch (value) {
      console.log(value)
    }
  },
  // 设置 editCanvasConfig 数据项
  setEditCanvasConfig (state, { key, value }) {
    state.editCanvasConfig[key] = value
  },
}

const actions = {
  // 计算缩放
  computedScale ({ state, commit }) {
    if (state.editCanvas.editLayoutDom) {
      // 现有展示区域
      const width = state.editCanvas.editLayoutDom.clientWidth - state.editCanvas.offset * 2 - 5
      const height = state.editCanvas.editLayoutDom.clientHeight - state.editCanvas.offset * 4

      // 用户设定大小
      const editCanvasWidth = state.editCanvasConfig.width
      const editCanvasHeight = state.editCanvasConfig.height

      // 需保持的比例
      const baseProportion = parseFloat((editCanvasWidth / editCanvasHeight).toFixed(5))
      const currentRate = parseFloat((width / height).toFixed(5))

      if (currentRate > baseProportion) {
        // 表示更宽
        const scaleWidth = parseFloat(((height * baseProportion) / editCanvasWidth).toFixed(5))
        commit('setScale', { scale: scaleWidth > 1 ? 1 : scaleWidth })
      } else {
        // 表示更高
        const scaleHeight = parseFloat((width / baseProportion / editCanvasHeight).toFixed(5))
        commit('setScale', { scale: scaleHeight > 1 ? 1 : scaleHeight })
      }
    } else {
      Message.warning('请先创建画布，再进行缩放')
    }
  },
  // 统一格式化处理入参 id
  idPreFormat ({ state }, id) {
    const idArr = []
    if (!id) {
      idArr.push(...state.targetChart.selectId)
      return idArr
    }
    if (isString(id)) idArr.push(id)
    if (isArray(id)) idArr.push(...id)
    return idArr
  },
}

const getters = {
  //  找到目标 id 数据的下标位置，id可为父级或子集数组（无则返回-1）
  fetchTargetIndex (state) {
    return function (id) {
      const targetId = id || (state.targetChart.selectId.length && state.targetChart.selectId[0]) || undefined
      if (!targetId) {
        loadingFinish()
        return -1
      }
      const targetIndex = state.componentList.findIndex(e => e.id === targetId)

      // 当前
      if (targetIndex !== -1) {
        return targetIndex
      } else {
        const length = state.componentList.length
        for (let i = 0; i < length; i++) {
          if (state.componentList[i].isGroup) {
            for (const cItem of (state.componentList[i]).groupList) {
              if (cItem.id === targetId) {
                return i
              }
            }
          }
        }
      }
      return -1
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
